package com.example.demo.APIs;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 三江对接api
 */
@Component
@Slf4j
public class UserSmartSanJiangAPIs {

     private static final String URL = "api.3jyun.com";

    /**
     *
     * @param urlpath 如 /agent/deviceType/deviceId/Alm
     * @param timestamp UNIX时间戳， 1970年1月1日0点以来的秒数；
     * @param deviceSecret 实际的设备密钥
     * @return 签名
     * @throws Exception
     */
    public String getSign(String  urlpath ,String timestamp ,String deviceSecret) throws Exception {
        // 拼接字符串
        String input = urlpath + timestamp + deviceSecret;
        // 计算 MD5
        return generateSignature(input);
    }

    /**
     * 三江推送链接回调
     * 注意嵌入该方法时一定要给这个地址【Sanjianyun/callBack】放行，被拦截了是无法访问的
     * @param requestBody
     * @return
     * 参考链接：https://doc.3jyun.com/#/%E7%94%A8%E6%88%B7%E6%96%87%E6%A1%A3/%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3/%E7%AC%AC%E4%B8%89%E6%96%B9%E5%B9%B3%E5%8F%B0%E6%8E%A5%E5%85%A5%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3
     */
    @PostMapping(value = "Sanjianyun/callBack")
    public String oneNetPush(@RequestBody Map<String, Object> requestBody) {
        log.info("3jianyun 回调：{}", requestBody);
        String streamId = (String) requestBody.get("streamId");
        //以下写业务逻辑
        //请根据文档https://doc.3jyun.com/#/%E7%94%A8%E6%88%B7%E6%96%87%E6%A1%A3/%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3/%E7%AC%AC%E4%B8%89%E6%96%B9%E5%B9%B3%E5%8F%B0%E6%8E%A5%E5%85%A5%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3
        //将采集的数据进行分析并放入数据库



        return "ok";
    }






    /**
     * 参数
     * @param input = urlpath + timestamp + deviceSecret
     * @return signature
     * @throws Exception
     */
    private static String generateSignature( String input) throws Exception {
        try {
            // 获取 MD5 实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算哈希值
            byte[] hashBytes = md.digest(input.getBytes());
            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }
}
